//
//  CardBannerView.swift
//  KaMengApplication
//
//  Created by DUONIU_MAC on 2019/1/12.
//  Copyright © 2019年 DUONIU_MAC. All rights reserved.
//

import UIKit
import FSPagerView

@objc protocol CardBannerViewDelegate {
    @objc optional func selectCardBanner(url:String) //选择轮播图
}

class CardBannerView: UIView {
    
    weak var delegate : CardBannerViewDelegate?
    
    fileprivate let cellId = "cardBannerCell"
    
    var dataArray = ["/data/upload/ads/top10_2018.jpg","/data/upload/ads/limitspeed_banner.jpg","/data/upload/index_pic/double11_2018.jpg","/data/upload/index_pic/season3_banner.jpg","/data/upload/index_pic/life.jpg"]
    
    var hrefArray = ["https://m.kameng98.com/mobile/zhuanti_top10_2018","https://m.kameng98.com/mobile/zhuanti_limitspeed","https://m.kameng98.com/mobile/zhuanti_double11_2018","https://m.kameng98.com/mobile/zhuanti_season3top10_2018","https://m.kameng98.com/mobile/center/i13"]

    fileprivate lazy var pageView : FSPagerView = {
        
        let pagerView = FSPagerView()
        pagerView.delegate = self
        pagerView.dataSource = self
        pagerView.register(CardBannerCell.self, forCellWithReuseIdentifier: cellId)
        pagerView.scrollDirection = .horizontal
        pagerView.itemSize = pagerView.frame.size
        pagerView.isInfinite = true //自动切换
        pagerView.automaticSlidingInterval = 5.0 //自动切换时间
        
        return pagerView
        
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.addSubview(pageView)
        
        pageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.zero)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension CardBannerView : FSPagerViewDelegate,FSPagerViewDataSource {
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        
        return dataArray.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: cellId, at: index) as? CardBannerCell
        cell?.backImageView.setUrlImage(with: kmHttps + dataArray[index], placeholder: UIImage.imageWithName("loading"))
        return cell!
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        
        self.delegate?.selectCardBanner!(url: hrefArray[index])
    }
    
}
